package voice;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class VoiceUtils {

    public static void stratVoice(String content, int type) {
        ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
        Dispatch sapo = sap.getObject();
        if (type == 0) {
            try {
                // 音量 0-100
                sap.setProperty("Volume", new Variant(100));
                // 语音朗读速度 -10 到 +10
                sap.setProperty("Rate", new Variant(0));
                Variant defalutVoice = sap.getProperty("Voice");
                Dispatch dispdefaultVoice = defalutVoice.toDispatch();
                Variant allVoices = Dispatch.call(sapo, "GetVoices");
                Dispatch dispVoices = allVoices.toDispatch();

                Dispatch setvoice = Dispatch.call(dispVoices, "Item",
                        new Variant(1)).toDispatch();
                ActiveXComponent voiceActivex = new ActiveXComponent(
                        dispdefaultVoice);
                ActiveXComponent setvoiceActivex = new ActiveXComponent(
                        setvoice);
                Variant item = Dispatch.call(setvoiceActivex, "GetDescription");
                // 执行朗读
                Dispatch.call(sapo, "Speak", new Variant(content));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                sapo.safeRelease();
                sap.safeRelease();
            }
        } else {
            // 停止
            try {
                Dispatch.call(sapo, "Speak", new Variant(content), new Variant(
                        2));
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        stratVoice("一二三四,one,two" ,0);

        ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
        try {
            // 音量 0-100
            sap.setProperty("Volume", new Variant(100));
            // 语音朗读速度 -10 到 +10
            sap.setProperty("Rate", new Variant(0));
            // 获取执行对象
            Dispatch sapo = sap.getObject();
            // 执行朗读
            Dispatch.call(sapo, "Speak", new Variant("你好，很高兴见到你。"));
            // 关闭执行对象
            sapo.safeRelease();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭应用程序连接
            sap.safeRelease();
        }
    }

}
